<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools>
        <template #slot-left>
          <span>共 19 条记录</span>
        </template>
        <template #slot-roght>
          <el-button v-power="'import'" type="danger" size="small" @click="$router.push('/excel')">导入excel</el-button>
          <el-button v-power="'export'" type="success" size="small" @click="outputFn">导出excel</el-button>
          <el-button type="primary" size="small" @click="clickFn">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 员工列表区域 -->
      <el-card class="employees-list">
        <el-table style="width:100%" border :data="employeesList" :default-sort="{prop:'mobile',order:'descending'}">
          <el-table-column label="序号" type="index" />
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="staffPhoto" label="头像">
            <template v-slot="scope">
              <!-- <img :src="scope.row.staffPhoto" class="staffPhone"> -->
              <image-holder :src="scope.row.staffPhoto" class="staffPhone" />
            </template>
          </el-table-column>
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式" :formatter="formatter" />
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间">
            <template v-slot="scope">
              {{ scope.row.timeOfEntry|forDateTime }}
            </template>
          </el-table-column>
          <el-table-column prop="" label="操作" width="150">
            <template v-slot="scope">
              <el-button
                type="text"
                size="small"
                @click="$router.push('/employees/detail?id='+scope.row.id
                )"
              >查看</el-button>
              <el-button type="text" size="small" @click="setEmp(scope.row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="delEmploy(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <!-- <el-row type="flex" justify="center" align="middle" style="height: 60px"> -->
        <!-- 分页区域 -->
        <el-pagination
          :current-page="query.page"
          :page-sizes="[3, 5, 8, 10]"
          :page-size="query.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
        <!-- 新增的弹框 -->
        <el-dialog
          title="新增"
          :visible.sync="showDialog"
          width="50%"
          @close="closeDialog"
        >
          <emp-dialog ref="addEmps" @close="showDialog=false" @addEvent="addFn" />
        </el-dialog>
        <!-- 分配角色的弹框 -->
        <el-dialog title="分配角色" :visible="showRoleDialog">
          <assign-role v-if="showRoleDialog" ref="assignRole" :user-id="userId" @close="showRoleDialog=false" />
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>
<script>
import { getEmployees, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
import empDialog from './empDialog.vue'
import dayjs from 'dayjs' // ES 2015
import AssignRole from './components/assignRole.vue'
export default {
  name: 'Employees',
  components: { empDialog, AssignRole },
  filters: {
    forDateTime: (value) => {
      return dayjs(value).format('YYYY-MM-DD')
    }
  },
  data() {
    return {
      query: {
        page: 1, // 页码
        size: 3 // 每页条数
      },
      employeesList: [], // 员工列表
      total: 0, // 数据总条数
      showDialog: false,
      showRoleDialog: false, // 分配角色
      userId: ''
    }
  },
  created() {
    this.getEmployees()
  },
  methods: {
    // 分配角色的方法
    setEmp(id) {
      this.userId = id
      this.showRoleDialog = true
      //  数据更新后,视图不会立刻更新,所有获取组件是获取不到的
      // this.$nextTick(() => {
      //   this.$refs.assignRole.getUserRoles()
      // })
    },
    // 导出方法
    transData(list) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const headerKeys = Object.keys(list[0])
      const header = headerKeys.map(item => {
        return map[item]
      })
      const data = list.map(item => {
        return Object.values(item)
      })
      return { header, data }
    },
    // 导方入法
    outputFn() {
      import('@/vendor/Export2Excel').then(async excel => {
        const res = await getEmployees(this.query)
        const excelObj = this.transData(res.data.rows)
        console.log(excelObj)
        // excel表示导入的模块对象
        excel.export_json_to_excel({
          header: excelObj.header, // 表头 必填
          data: excelObj.data, // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    clickFn() {
      this.showDialog = true
    },
    // 删除员工
    async delEmploy(id) {
      const tipRes = await this.$confirm('此操作将永久删除此员工吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (tipRes === 'cancel') {
        this.$message('您取消删除')
      } else {
        // 调用接口
        const res = await delEmployee(id)
        if (this.employeesList.length === 1) {
          this.query.page--
        }
        if (this.query.page <= 0) {
          this.query.page = 1
        }
        this.$message.success(res.message)
        // 渲染列表
        this.getEmployees()
      }
    },

    // 格式化
    formatter(row, column, cellValue, index) {
      const obj = EmployeeEnum.hireType.find(item => item.id === Number(cellValue))
      return obj ? obj.value : '未识别'
    },
    // 获取员工列表
    async getEmployees() {
      const res = await getEmployees(this.query)

      this.employeesList = res.data.rows
      this.total = res.data.total
    },
    // 每页显示的条数发生改变时触发
    handleSizeChange(newSize) {
      this.query.size = newSize
      this.getEmployees()
    },

    // 当前页面发生改变时触发
    handleCurrentChange(newPage) {
      this.query.page = newPage
      this.getEmployees()
    },
    // 添加数据事件成功
    addFn() {
      this.showDialog = false
      // 渲染列表
      this.getEmployees()
    },
    // 关闭前的回调
    closeDialog() {
      // console.log(this.$refs.addEmps)
      this.$refs.addEmps.restForm()
    }
  }
}
</script>

<style lang="scss" scoped>
.employees-list{
  padding:10px;
  margin-top: 20px;
}
.staffPhone{
  width:80px;
  height:80px;
  border-radius: 50%;
}
</style>
